package com.costeaalex.MIDlets.remote.communication;

import java.io.*;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class BluetoothConnection implements CommunicationManager
	{
	
	private DataInputStream in;
	private DataOutputStream out;
	private StreamConnection mainConn;
	
	public BluetoothConnection(String connectionURL)
		{
		try
			{
			mainConn=(StreamConnection) Connector.open(connectionURL, Connector.READ_WRITE);
			in=mainConn.openDataInputStream();
			out=mainConn.openDataOutputStream();
			}
		catch (IOException e)
			{
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		}
	
	/* (non-Javadoc)
	 * @see com.costeaalex.MIDlets.remote.connection.CommunicationManager#sendData(int)
	 */
	public synchronized int send(int data)
		{
		try
			{
			//out.write(data);
			out.write(data);
			out.flush();
			return 1;
			}
		catch (IOException e)
			{
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		return 0;
		}
	
	public synchronized int send(byte[] data)
		{
		try
			{
			//out.write(data);
			out.write(data);
			out.flush();
			return 1;
			}
		catch (IOException e)
			{
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		return 0;
		}
	
	/* (non-Javadoc)
	 * @see com.costeaalex.MIDlets.remote.connection.CommunicationManager#receiveData()
	 */
	public int receive()
		{
		try
			{
			return in.read();
			}
		catch (IOException e)
			{
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		return 0;
		}
	
	/* (non-Javadoc)
	 * @see com.costeaalex.MIDlets.remote.connection.CommunicationManager#receiveDataBlock()
	 */
	public byte[] receiveBlock()
		{
		byte[] data;
		try
			{
			data = new byte[in.available()]; 
			in.read(data);
			return data;
			}
		catch (Exception e)
			{
			// TODO Auto-generated catch block
			//e.printStackTrace();
			}
		return null;
		}
	
	/* (non-Javadoc)
	 * @see com.costeaalex.MIDlets.remote.connection.CommunicationManager#getAvailableData()
	 */
	public int getAvailableData()
		{
		try
			{
			return in.available();
			}
		catch (IOException e)
			{
			e.printStackTrace();
			}
		return 0;
		}
	
	/* (non-Javadoc)
	 * @see com.costeaalex.MIDlets.remote.connection.CommunicationManager#close()
	 */
	public void close() throws IOException
		{
		in.close();
		out.close();
		mainConn.close();
		}
	
	}
